package com.flight.controller;

import com.flight.model.entity.Cabin;
import com.flight.model.entity.Flight;
import com.flight.model.service.BookingService;
import com.flight.model.service.CabinService;
import com.flight.model.service.FlightService;
import com.flight.model.service.PassengerService;
import com.flight.model.service.impl.BookingServiceImpl;
import com.flight.model.service.impl.CabinServiceImpl;
import com.flight.model.service.impl.FlightServiceImpl;
import com.flight.model.service.impl.PassengerServiceImpl;
import com.flight.util.Constant;
import com.flight.view.BookingPanel;
import com.flight.view.FlightSearchPanel;
import com.flight.view.MainFrame;
import com.flight.view.components.FlightTable;
import com.flight.view.components.MessageDialog;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.List;
import javax.swing.*;

public class FlightSearchController {
    private FlightSearchPanel searchPanel;
    private MainFrame mainFrame;
    private String passengerId;
    private FlightTable flightTable;
    private JButton backBtn; // 新增：返回主界面按钮

    // 服务层对象
    private FlightService flightService = new FlightServiceImpl();
    private CabinService cabinService = new CabinServiceImpl();
    private BookingService bookingService = new BookingServiceImpl();
    private PassengerService passengerService = new PassengerServiceImpl();

    public FlightSearchController(MainFrame mainFrame, String passengerId) {
        this.mainFrame = mainFrame;
        this.passengerId = passengerId;
        this.searchPanel = new FlightSearchPanel();
        this.flightTable = new FlightTable();
        initUI(); // 初始化界面（包含返回按钮）
        bindEvents(); // 绑定所有事件（查询、订票、返回）
    }

    private void initUI() {
        searchPanel.setLayout(new BorderLayout(10, 10)); // 组件间距10px
        searchPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 顶部面板：查询条件 + 返回按钮
        JPanel topPanel = new JPanel(new BorderLayout(10, 10));

        // 左侧：查询条件面板（复用原有）
        topPanel.add(searchPanel.getConditionPanel(), BorderLayout.CENTER);

        // 右侧：返回主界面按钮（新增）
        JPanel backBtnPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        backBtn = new JButton("返回主界面");
        backBtn.setPreferredSize(new Dimension(120, 30)); // 按钮大小
        backBtnPanel.add(backBtn);
        topPanel.add(backBtnPanel, BorderLayout.EAST);

        // 添加顶部面板到查询面板
        searchPanel.add(topPanel, BorderLayout.NORTH);

        // 中间：航班表格（原有逻辑不变）
        searchPanel.add(new JScrollPane(flightTable), BorderLayout.CENTER);
    }

    private void bindEvents() {
        // 1. 查询按钮事件（原有逻辑不变）
        searchPanel.addSearchListener(e -> handleFlightSearch());

        // 2. 订票按钮事件（原有逻辑不变）
        flightTable.setBookingActionListener(e -> handleBooking());

        // 3. 新增：返回主界面按钮事件
        backBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 切换回主界面的首页面板（依赖 MainFrame 的 getMainPanel() 方法）
                mainFrame.setContentPane(mainFrame.getMainPanel());
                mainFrame.validate(); // 刷新界面
                mainFrame.repaint();
            }
        });
    }

    // 原有：处理航班查询（逻辑不变）
    private void handleFlightSearch() {
        String depCity = searchPanel.getDepCity();
        String arrCity = searchPanel.getArrCity();
        Date depDate = searchPanel.getDepDate();

        if (depCity.isEmpty() || arrCity.isEmpty()) {
            MessageDialog.showError(searchPanel, "出发地和目的地不能为空！");
            return;
        }
        if (depDate == null) {
            MessageDialog.showError(searchPanel, "请输入正确的日期格式（yyyy-MM-dd）！");
            return;
        }

        List<Flight> flights = flightService.searchFlights(depCity, arrCity, depDate);
        if (flights.isEmpty()) {
            MessageDialog.showInfo(searchPanel, "未查询到符合条件的航班");
        } else {
            flightTable.setFlightData(flights);
            MessageDialog.showInfo(searchPanel, "查询到" + flights.size() + "个航班");
        }
    }

    // 原有：处理订票逻辑（逻辑不变，仅优化界面切换体验）
    private void handleBooking() {
        Flight selectedFlight = flightTable.getSelectedFlight();
        if (selectedFlight == null) {
            MessageDialog.showError(searchPanel, "请选择航班！");
            return;
        }

        List<Cabin> cabins = cabinService.getByFlightNo(selectedFlight.getFlightNo());
        if (cabins.isEmpty()) {
            MessageDialog.showError(searchPanel, "该航班无可用舱位！");
            return;
        }

        BookingPanel bookingPanel = new BookingPanel(selectedFlight, cabins);
        bookingPanel.addSubmitListener(e -> {
            if (bookingPanel.checkCabinValid()) {
                Cabin cabin = bookingPanel.getSelectedCabin();
                String orderId = bookingService.createOrder(passengerId, cabin.getCabinId(), Constant.ORDER_METHOD_APP);
                if (orderId != null) {
                    MessageDialog.showInfo(bookingPanel, "订单创建成功：" + orderId);
                    // 订票成功后返回查询航班界面
                    mainFrame.setContentPane(searchPanel);
                    mainFrame.validate();
                }
            }
        });

        // 打开订票面板
        mainFrame.setContentPane(bookingPanel);
        mainFrame.validate();
    }

    // 暴露查询面板供外部访问（如 BookingController）
    public FlightSearchPanel getSearchPanel() {
        return searchPanel;
    }

    // 新增：暴露返回按钮供外部绑定事件（可选，如需在 BookingController 统一管理）
    public JButton getBackBtn() {
        return backBtn;
    }

}






//package com.flight.controller;
//
//import com.flight.model.entity.Cabin;
//import com.flight.model.entity.Flight;
//import com.flight.model.entity.Passenger;
//import com.flight.model.service.BookingService;
//import com.flight.model.service.CabinService;
//import com.flight.model.service.FlightService;
//import com.flight.model.service.PassengerService;
//import com.flight.model.service.impl.BookingServiceImpl;
//import com.flight.model.service.impl.CabinServiceImpl;
//import com.flight.model.service.impl.FlightServiceImpl;
//import com.flight.model.service.impl.PassengerServiceImpl;
//import com.flight.util.Constant;
//import com.flight.view.BookingPanel;
//import com.flight.view.FlightSearchPanel;
//import com.flight.view.MainFrame;
//import com.flight.view.components.FlightTable;
//import com.flight.view.components.MessageDialog;
//
//import java.awt.*; // 补充AWT相关类导入
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
//import java.util.Date;
//import java.util.List;
//import javax.swing.JScrollPane; // 导入滚动面板类
//
//public class FlightSearchController {
//    private FlightSearchPanel searchPanel;
//    private MainFrame mainFrame;
//    private String passengerId;
//    private FlightTable flightTable;
//
//    // 服务层对象
//    private FlightService flightService = new FlightServiceImpl();
//    private CabinService cabinService = new CabinServiceImpl();
//    private BookingService bookingService = new BookingServiceImpl();
//    private PassengerService passengerService = new PassengerServiceImpl();
//
//    public FlightSearchController(MainFrame mainFrame, String passengerId) {
//        this.mainFrame = mainFrame;
//        this.passengerId = passengerId;
//        this.searchPanel = new FlightSearchPanel();
//        this.flightTable = new FlightTable();
//        initUI();
//        bindEvents();
//    }
//
//    private void initUI() {
//        searchPanel.setLayout(new BorderLayout()); // 补充BorderLayout导入后可正常使用
//        searchPanel.add(searchPanel.getConditionPanel(), BorderLayout.NORTH);
//        searchPanel.add(new JScrollPane(flightTable), BorderLayout.CENTER);
//    }
//
//    private void bindEvents() {
//        // 查询按钮事件
//        searchPanel.addSearchListener(e -> handleFlightSearch());
//
//        // 订票按钮事件
//        flightTable.setBookingActionListener(e -> handleBooking());
//    }
//
//    private void handleFlightSearch() {
//        String depCity = searchPanel.getDepCity();
//        String arrCity = searchPanel.getArrCity();
//        Date depDate = searchPanel.getDepDate();
//
//        if (depCity.isEmpty() || arrCity.isEmpty()) {
//            MessageDialog.showError(searchPanel, "出发地和目的地不能为空！");
//            return;
//        }
//        if (depDate == null) {
//            MessageDialog.showError(searchPanel, "请输入正确的日期格式（yyyy-MM-dd）！");
//            return;
//        }
//
//        List<Flight> flights = flightService.searchFlights(depCity, arrCity, depDate);
//        if (flights.isEmpty()) {
//            MessageDialog.showInfo(searchPanel, "未查询到符合条件的航班");
//        } else {
//            flightTable.setFlightData(flights);
//            MessageDialog.showInfo(searchPanel, "查询到" + flights.size() + "个航班");
//        }
//    }
//
//    private void handleBooking() {
//        Flight selectedFlight = flightTable.getSelectedFlight();
//        if (selectedFlight == null) {
//            MessageDialog.showError(searchPanel, "请选择航班！");
//            return;
//        }
//
//        List<Cabin> cabins = cabinService.getByFlightNo(selectedFlight.getFlightNo());
//        if (cabins.isEmpty()) {
//            MessageDialog.showError(searchPanel, "该航班无可用舱位！");
//            return;
//        }
//
//        BookingPanel bookingPanel = new BookingPanel(selectedFlight, cabins);
//        bookingPanel.addSubmitListener(e -> {
//            if (bookingPanel.checkCabinValid()) {
//                Cabin cabin = bookingPanel.getSelectedCabin();
//                String orderId = bookingService.createOrder(passengerId, cabin.getCabinId(), Constant.ORDER_METHOD_APP);
//                if (orderId != null) {
//                    MessageDialog.showInfo(bookingPanel, "订单创建成功：" + orderId);
//                    mainFrame.setContentPane(searchPanel);
//                    mainFrame.validate();
//                }
//            }
//        });
//
//        mainFrame.setContentPane(bookingPanel);
//        mainFrame.validate();
//    }
//
//    public FlightSearchPanel getSearchPanel() {
//        return searchPanel;
//    }
//}